package com.project.workjob.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.project.workjob.dto.ConfigDto;
import com.project.workjob.dto.GjxlParam;
import com.project.workjob.dto.GjxlYbParam;
import com.project.workjob.entity.Gjxl;
import com.project.workjob.entity.GjxlYb;
import com.project.workjob.service.GjxlService;
import com.project.workjob.service.GjxlYbService;
import com.project.workjob.util.GjxlYbHttpResult;
import com.project.workjob.util.HttpUtil;
import com.project.workjob.util.GjxlYbUtil;
import com.project.workjob.util.RestResult;
import org.apache.commons.io.FileUtils;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/workjob/gjxlyb/")
public class GjxlYbController {

    @Resource
    ConfigDto configDto;
    @Resource
    GjxlYbService gjxlYbService;
    @Resource
    GjxlService gjxlService;

    @PostMapping("exec")
    public RestResult exec(@RequestBody GjxlYbParam param) {
        String url = configDto.getGjxlybHost() + "?report_time_start=" + param.getStartDate() + "&report_time_end=" + param.getEndDate();
        HttpUtil httpUtil = new HttpUtil(url, configDto.getTimeout());
        String token = configDto.getToken();
        try {
            GjxlYbHttpResult result = httpUtil.getGjxlYbUrl(token);
            List<List<String>> dataList = result.getData().getResult().getValues();
            List<GjxlYb> gjxlYbList = GjxlYbUtil.getData(dataList);
            if (gjxlYbList != null && gjxlYbList.size() > 0) {
                gjxlYbService.deleteByDate(gjxlYbList.get(0).getReport_time());
                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                calendar.setTime(df.parse(gjxlYbList.get(0).getReport_time()));
                calendar.add(Calendar.MONTH, -1);
                String beforeDate = df.format(calendar.getTime());
                List<GjxlYb> gjxlYbList1 = gjxlYbService.getListByDate(beforeDate);
                if (gjxlYbList1.size() > 0) {
                    for (GjxlYb gjxlYb : gjxlYbList) {
                        for (GjxlYb gjxlYb1 : gjxlYbList1) {
                            if (gjxlYb.getNo2().equals(gjxlYb1.getNo2())) {
                                gjxlYb.setJgxlid(gjxlYb1.getJgxlid());
                                break;
                            }
                        }
                    }
                }
                List<GjxlYb> gjxlYbNullList = gjxlYbList.stream().filter(item -> item.getJgxlid() == null).collect(Collectors.toList());
                if (gjxlYbNullList.size() > 0) {
                    for (GjxlYb gjxlYb : gjxlYbNullList) {
                        GjxlParam gjxlParam = new GjxlParam();
                        gjxlParam.setName(gjxlYb.getNo2());
                        List<Gjxl> gjxl1 = gjxlService.getJgxlidByName(gjxlParam);
                        if (gjxl1.size() > 0) {
                            gjxlYb.setJgxlid(gjxl1.get(0).getJgxlid());
                        }
                        if (gjxlYb.getJgxlid() == null) {
                            List<Gjxl> gjxl2 = gjxlService.getJgxlidByYgName(gjxlParam);
                            if (gjxl2.size() > 0) {
                                gjxlYb.setJgxlid(gjxl2.get(0).getJgxlid());
                            }
                        }
                    }
                }
                gjxlYbService.insert(gjxlYbList);
            }
            return RestResult.ok();
        } catch (Exception e) {
            return RestResult.error(e.getMessage());
        }
    }

    @PostMapping("test")
    public RestResult test() {
        String url = "http://localhost:18080/api/workjob/gjxlyb/data/test";
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        headers.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
        HttpEntity httpEntity = new HttpEntity(headers);
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(configDto.getTimeout());
        httpRequestFactory.setConnectTimeout(configDto.getTimeout());
        httpRequestFactory.setReadTimeout(configDto.getTimeout());
        httpRequestFactory.setBufferRequestBody(false);
        RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
        try {
            ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class);
            if (response.getStatusCode() != HttpStatus.OK) {
                throw new Exception("请求失败:" + response.getStatusCodeValue());
            }
            GjxlYbHttpResult httpResult = JSONObject.parseObject(JSON.toJSONString(response.getBody()), GjxlYbHttpResult.class);
            List<List<String>> dataList = httpResult.getData().getResult().getValues();
            List<GjxlYb> gjxlYbList = GjxlYbUtil.getData(dataList);
            if (gjxlYbList != null && gjxlYbList.size() > 0) {
                gjxlYbService.deleteByDate("2025-07-01 00:00:00");
                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                calendar.setTime(df.parse("2025-07-01 00:00:00"));
                calendar.add(Calendar.MONTH, -1);
                String beforeDate = df.format(calendar.getTime());
                List<GjxlYb> gjxlYbList1 = gjxlYbService.getListByDate(beforeDate);
                if (gjxlYbList1.size() > 0) {
                    for (GjxlYb gjxlYb : gjxlYbList) {
                        for (GjxlYb gjxlYb1 : gjxlYbList1) {
                            if (gjxlYb.getNo2().equals(gjxlYb1.getNo2())) {
                                gjxlYb.setJgxlid(gjxlYb1.getJgxlid());
                                break;
                            }
                        }
                    }
                }
                List<GjxlYb> gjxlYbNullList = gjxlYbList.stream().filter(item -> item.getJgxlid() == null).collect(Collectors.toList());
                if (gjxlYbNullList.size() > 0) {
                    for (GjxlYb gjxlYb : gjxlYbNullList) {
                        GjxlParam gjxlParam = new GjxlParam();
                        gjxlParam.setName(gjxlYb.getNo2());
                        List<Gjxl> gjxl1 = gjxlService.getJgxlidByName(gjxlParam);
                        if (gjxl1.size() > 0) {
                            gjxlYb.setJgxlid(gjxl1.get(0).getJgxlid());
                        }
                        if (gjxlYb.getJgxlid() == null) {
                            List<Gjxl> gjxl2 = gjxlService.getJgxlidByYgName(gjxlParam);
                            if (gjxl2.size() > 0) {
                                gjxlYb.setJgxlid(gjxl2.get(0).getJgxlid());
                            }
                        }
                    }
                }
                gjxlYbService.insert(gjxlYbList);
            }
            return RestResult.ok();
        } catch (Exception e) {
            return RestResult.error(e.getMessage());
        }
    }

    @PostMapping("data/test")
    public String dataTest() {
        try {
            File file = ResourceUtils.getFile("classpath:gjxlyb_test.json");
            String json = FileUtils.readFileToString(file, "UTF-8");
            return json;
        } catch (Exception e) {
            return e.getMessage();
        }
    }
}
